package view.ventanas_principales.panels;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import com.mxrck.autocompleter.TextAutoCompleter;

import model.Alumno;
import model.Area;
import model.Contacto;
import model.Curso;
import model.PersonalAdministrativo;
import model.comunication.IAlumno;
import model.comunication.IContacto;
import model.utils.CalendarTable;
import model.utils.Util;
import view.contacto.ConsultaContacto;
import java.awt.BorderLayout;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

public class HistorialContactoPanel extends JPanel {

	private static final long serialVersionUID = 1L;
	private IContacto comunicationContacto;
	private IAlumno comunicationAlumno;
	private Map<Integer, Contacto> contactos;
	private JTable table;
	private PersonalAdministrativo personalAdministrativo;
	private JComboBox<String> comboBox;
	private DefaultTableModel model;
	private JTextField textFieldAlumno;
	private TableRowSorter<TableModel> rowSorter;
	private TextAutoCompleter textAutoAcompleter;

	public HistorialContactoPanel() {
		constructor();
		inicialize();
	}

	public HistorialContactoPanel(PersonalAdministrativo personalAdministrativo) {
		constructor();
		this.personalAdministrativo = personalAdministrativo;
		inicialize();
	}

	private void constructor() {
		this.contactos = new HashMap<Integer, Contacto>();
		this.comunicationContacto = IContacto.getInstance();
		this.comunicationAlumno = IAlumno.getInstance();
	}

	private void inicialize() {
		setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane = new JScrollPane();
		this.add(scrollPane);

		table = new JTable();
		table.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "id", "Administrativo", "Fecha", "Alumno", "Interes" }) {

			@Override
			public Class getColumnClass(int columna) {
				if (columna == 2) {
					return Calendar.class;

				}
				return String.class;
			}
		});
		table.getColumnModel().getColumn(0).setPreferredWidth(0);
		table.getColumnModel().getColumn(0).setMinWidth(0);
		table.getColumnModel().getColumn(0).setMaxWidth(0);
		model = (DefaultTableModel) table.getModel();
		rowSorter = new TableRowSorter<TableModel>(model);

		table.setRowSorter(rowSorter);
		table.getTableHeader().setReorderingAllowed(false);
		scrollPane.setViewportView(table);

		JPanel buttonPanel = new JPanel();
		FlowLayout flowLayout_1 = (FlowLayout) buttonPanel.getLayout();
		add(buttonPanel, BorderLayout.SOUTH);

		JButton btnVer = new JButton("Ver");
		buttonPanel.add(btnVer);
		btnVer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int selectRow = table.getSelectedRow();
				if (!(selectRow < 0)) {
					String value = (String) table.getValueAt(table.getSelectedRow(), 0);
					Contacto contacto = contactos.get(new Integer(value));
					ConsultaContacto consultaContacto = new ConsultaContacto(contacto);

				}

			}
		});

		JPanel comboPanel = new JPanel();
		add(comboPanel, BorderLayout.NORTH);
		comboPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		comboBox = new JComboBox<String>();
		comboBox.setModel(new DefaultComboBoxModel(new String[] { "Mis Contactos", "Todos los Contactos" }));
		comboPanel.add(comboBox);

		textFieldAlumno = new JTextField();
		textFieldAlumno.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent arg0) {
				rowSorter.setRowFilter(RowFilter.regexFilter("(?<![^ ])(?=[^ ])((?i)" + textFieldAlumno.getText() + ")", 3));
			}
		});
		textFieldAlumno.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				rowSorter.setRowFilter(RowFilter.regexFilter("(?<![^ ])(?=[^ ])((?i)" + textFieldAlumno.getText() + ")", 3));
				// loadAlumno();
			}
		});
		JLabel lblAlumno = new JLabel("Alumno:");
		comboPanel.add(lblAlumno);
		comboPanel.add(textFieldAlumno);
		textFieldAlumno.setColumns(10);
		textAutoAcompleter = new TextAutoCompleter(textFieldAlumno);
		for (Alumno alumno : comunicationAlumno.getAllAlumnos()) {
			String nombreAlumno = Util.obtainName(alumno);
			textAutoAcompleter.addItem(nombreAlumno);
		}

		textAutoAcompleter.setCaseSensitive(false);
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				loadContactos();
			}
		});
		loadContactos();
	}

	public void loadContactos() {

		this.model.setRowCount(0);
		String selection = (String) comboBox.getSelectedItem();
		List<Contacto> contactosDB = new ArrayList<Contacto>();
		if (selection.equals("Todos los Contactos")) {
			contactosDB = this.comunicationContacto.getAllContactos();
		} else if (selection.equals("Mis Contactos")) {
			contactosDB = this.comunicationContacto.getContactos(personalAdministrativo);
		}

		for (Contacto contacto : contactosDB) {
			this.contactos.put(contacto.getId(), contacto);

			PersonalAdministrativo administrativo = contacto.getPersonalAdministrativo();
			Alumno alumno = contacto.getAlumno();

			List<Area> areas = contacto.getAreas();
			String areasString = "";
			if (areas != null) {
				for (Area area : areas) {

					areasString += area.getNombre();
				}
			}
			String cursosString = "";
			List<Curso> cursos = contacto.getCursos();
			if (cursos != null) {
				for (Curso curso : cursos) {
					cursosString += curso.getNombre();
				}
			}
			CalendarTable caltable = new CalendarTable();
			caltable.setTimeInMillis(contacto.getFecha().getTimeInMillis());

			String intereses = !"".equals(cursosString) ? "Cursos de interes: " + cursosString : "";
			intereses += !"".equals(areasString) ? "Areas de interes: " + areasString : "";
			Object[] lista = { contacto.getId().toString(), Util.obtainName(administrativo), caltable, Util.obtainName(alumno), intereses };
			model.addRow(lista);
		}

	}

	public void loadAlumno() {

		this.model.setRowCount(0);

		String selection = (String) comboBox.getSelectedItem();
		List<Contacto> contactosDB = new ArrayList<Contacto>();
		// if (selection.equals("Todas las Tareas")) {
		contactosDB = this.comunicationContacto.getAllContactos();
		// } else if (selection.equals("Mis Tareas")) {
		// contactosDB = this.comunicationContacto.getContactos(personalAdministrativo);
		// }
		List<Alumno> alumnos = comunicationAlumno.findAlumnos(textFieldAlumno.getText(), "", "", "");
		for (Alumno alumno : alumnos) {

			for (Contacto contacto : contactosDB) {
				this.contactos.put(contacto.getId(), contacto);

				PersonalAdministrativo administrativo = contacto.getPersonalAdministrativo();
				// Alumno alumno = contacto.getAlumno();
				contacto.getAlumno();
				List<Area> areas = contacto.getAreas();
				String areasString = "";
				if (areas != null) {
					for (Area area : areas) {

						areasString += area.getNombre();
					}
				}
				String cursosString = "";
				List<Curso> cursos = contacto.getCursos();
				if (cursos != null) {
					for (Curso curso : cursos) {
						cursosString += curso.getNombre();
					}
				}

				CalendarTable caltable = new CalendarTable();
				caltable.setTimeInMillis(contacto.getFecha().getTimeInMillis());

				String intereses = !"".equals(cursosString) ? "Cursos de interes: " + cursosString : "";
				intereses += !"".equals(areasString) ? "Areas de interes: " + areasString : "";
				Object[] lista = { contacto.getId().toString(), Util.obtainName(administrativo), caltable, Util.obtainName(alumno), intereses };
				model.addRow(lista);
			}
			// }
		}

		// public void alumno() {
		// List<Alumno> alumnos = comunicationAlumno.findAlumnos(textNombre.getText(),"","","");
		// for (Alumno alumno : alumnos) {
		//
		// }
		// }
	}
}
